package cn.longg.service.impl;

import cn.longg.entity.Dept;
import cn.longg.entity.Meeting;
import cn.longg.entity.MeetingJoin;
import cn.longg.entity.User;
import cn.longg.mapper.DeptMapper;
import cn.longg.mapper.MeetingJoinMapper;
import cn.longg.mapper.MeetingMapper;
import cn.longg.mapper.UserMapper;
import cn.longg.service.IMeetingService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Service
@Transactional
public class MeetingServiceImpl extends BaseServiceImpl<Meeting> implements IMeetingService {

    @Autowired
    private MeetingMapper meetingMapper;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private MeetingJoinMapper meetingJoinMapper;

    @Override
    public PageInfo selectByPage(int page, int pageSize, Meeting meeting) {
        PageHelper.startPage(page,pageSize);
        List<Meeting> meetings = meetingMapper.selectByPage(meeting);
        for (Meeting meeting1 : meetings) {
            List<User> userList = userMapper.selectByDeptId(meeting1.getDeptId());
            meeting1.setShouldArrive(userList.size());
            MeetingJoin meetingJoin = new MeetingJoin();
            meetingJoin.setcId(meeting1.getId());
            List<MeetingJoin> select = meetingJoinMapper.select(meetingJoin);
            meeting1.setArrived(select.size());
            meeting1.setNotArrive(meeting1.getShouldArrive() - meeting1.getArrived());
        }
        return new PageInfo(meetings);
    }

    @Override
    public void checkStatus() {
        List<Meeting> meetings = selectAll();
        List<Integer> beginMeeting = new ArrayList<>();
        List<Integer> finishMeeting = new ArrayList<>();
        for (Meeting meeting : meetings) {
            if(meeting.getStartTime().before(new Date()) && new Date().before(meeting.getEndTime()) && meeting.getStatus() != 1){
                beginMeeting.add(meeting.getId());
            }
            if(meeting.getEndTime().before(new Date()) && meeting.getStatus() != 2){
                finishMeeting.add(meeting.getId());
            }
        }
        if(beginMeeting.size() > 0){
            meetingMapper.updateBegin(beginMeeting);
        }
        if(finishMeeting.size() > 0){
            meetingMapper.updateFinish(finishMeeting);
        }

    }
}
